package com.y3k.servlet;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.Iterator;
import java.util.Timer;

import javax.servlet.Servlet;
import javax.servlet.ServletConfig;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;

import org.apache.log4j.Logger;

import com.y3k.model.Notification;
import com.y3k.utils.ConfigurationUtil;

public class EmailScheduleServlet implements Servlet {

	public static final Logger log = Logger.getLogger(EmailScheduleServlet.class);

	private ServletContext servletContext;

	private Timer timer;

	public void init(ServletConfig config) throws ServletException {
		this.timer = new Timer();
		this.servletContext = config.getServletContext();
	}

	public void service(ServletRequest request, ServletResponse response) throws ServletException, IOException {
		log.info("EmailScheduleServlet service");

		for (Iterator<Notification> it = ConfigurationUtil.NOTIFICATIONS.iterator(); it.hasNext();) {
			Notification notification = it.next();

			notification.setMailBody(getTemplate(notification.getTemplate()));
			EmailTask emailTask = new EmailTask(notification);
			timer.schedule(emailTask, 0, notification.getCheckTime());
		}
	}

	private String getTemplate(String path) throws ServletException {
		String line = null;
		StringBuffer sb = new StringBuffer();

		String resource = ConfigurationUtil.PATH + "/mail" + path;
		InputStream is = servletContext.getResourceAsStream(resource);

		try {
			BufferedReader reader = new BufferedReader(new InputStreamReader(is, "UTF-8"));
			while ((line = reader.readLine()) != null) {
				sb.append(line).append("\n");
			}
		} catch (UnsupportedEncodingException e) {
			throw new ServletException(e);
		} catch (IOException e) {
			throw new ServletException(e);
		}
		return sb.toString();
	}

	public void destroy() {
		log.info("EmailScheduleServlet destroy");
	}

	public String getServletInfo() {
		return null;
	}

	public ServletConfig getServletConfig() {
		return null;
	}
}